package com.wolfsea.curveviewcase
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View

/**
 *@desc  LeafView
 *@author liuliheng
 *@time 2022/12/14  16:31
 **/
class LeafView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null) :
    View(context, attributeSet) {

    private val leafPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            style = Paint.Style.FILL
            color = context.resources.getColor(R.color.purple_200)
        }
    }

    private val path by lazy {
        Path()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val mWidth = context.resources.getDimension(R.dimen.dp_60).toInt()
        val mHeight = context.resources.getDimension(R.dimen.dp_80).toInt()
        setMeasuredDimension(mWidth, mHeight)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            val centerX = width / 2F
            val centerY = height / 2F
            val radius = Math.max(width, height) / 2

            path.moveTo(0F, 0F)

            val leftCtrY = -(radius * 7) / 10.0F
            val leftCtrX = -(Math.abs(leftCtrY) * Math.tan(Math.toRadians(30.toDouble()))).toFloat()

            val lastX = 0F
            val lastY = -radius.toFloat()

            val rightCtrY = -(radius * 7) / 10.0F
            val rightCtrX =
                (Math.abs(rightCtrY) * Math.tan(Math.toRadians(30.toDouble()))).toFloat()

            path.quadTo(leftCtrX, leftCtrY, lastX, lastY)
            path.quadTo(rightCtrX, rightCtrY, 0F, 0F)
            path.close()

            path.fillType = Path.FillType.WINDING
            val restoreId = this.save()
            val style = leafPaint.style
            translate(centerX, centerY + Math.abs(rightCtrY) * 2 / 3)
            drawPath(path, leafPaint)
            leafPaint.style = style
            this.restoreToCount(restoreId)
        }
    }

}